/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lansupportclient;

import ObjectHandler.LanSupportMessage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Cong
 */
public class ShellCmd {

    private static boolean fl = true;
    private Socket sendSocket;
    private LanSupportMessage Message = new LanSupportMessage(LanSupportMessage.ShellMessage);
    private LanSupportMessage Refuse = new LanSupportMessage(LanSupportMessage.ClientRefuseShell);

    public ShellCmd(Socket sendSocket) {
        this.sendSocket = sendSocket;
    }

    public void Exec(String cmd) {
        if (fl) {
            fl = false;
            byte[] data;
            try {
                Process process = Runtime.getRuntime().exec("cmd /c " + cmd);
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(process.getInputStream()));
                BufferedReader errors = new BufferedReader(
                        new InputStreamReader(process.getErrorStream()));
                String out;
                while ((out = errors.readLine()) != null) {
                    data = out.getBytes();
                    Message.setData(data);
                    Message.Send(sendSocket);
                }
                while ((out = reader.readLine()) != null) {
                    data = out.getBytes();
                    Message.setData(data);
                    Message.Send(sendSocket);
                }
            } catch (IOException ex) {
                Logger.getLogger(ShellCmd.class.getName()).log(Level.SEVERE, null, ex);
            }
            fl = true;
        } else {
            Refuse.Send(sendSocket);
        }
    }
}
